<template>
  <div class="login-container">
    <!-- 左侧轮播图区域 -->
    <div class="left-panel">
      <el-carousel
        :interval="5000"
        arrow="never"
        indicator-position="none"
        height="100vh"
        @change="handleCarouselChange"
      >
        <el-carousel-item v-for="(item, index) in bgList" :key="index">
          <div class="carousel-content">
            <!-- 渐进式加载优化 -->
            <img
              :src="item.image"
              class="carousel-image"
              alt="系统登录背景图"
              loading="lazy"
              :style="{ opacity: currentBgIndex === index ? 1 : 0 }"
            />
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 右侧登录表单区域 -->
    <div class="right-panel">
      <div class="login-form">
        <!-- 动态标题 -->
        <h1 class="title">
          <span class="brand">智慧酒店管理系统</span>
          <div class="version">v3.0.0</div>
        </h1>

        <!-- 登录表单主体 -->
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          @keyup.enter="handleSubmit"
        >
          <!-- 用户名输入 -->
          <el-form-item prop="username">
            <el-input
              v-model="formData.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              clearable
              autocomplete="username"
              @focus="handleInputFocus"
            />
          </el-form-item>

          <!-- 密码输入 -->
          <el-form-item prop="password">
            <el-input
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
              clearable
              autocomplete="current-password"
              @focus="handleInputFocus"
            />
            <!-- 密码强度提示 -->
            <transition name="el-zoom-in-top">
              <div v-show="formData.password" class="password-strength">
                安全等级：{{ passwordStrength }}
              </div>
            </transition>
          </el-form-item>

          <!-- 操作功能区 -->
          <div class="action-bar">
            <el-checkbox v-model="formData.remember" label="保持登录" />
          </div>

          <!-- 提交按钮 -->
          <el-button
            type="primary"
            class="submit-btn"
            :loading="isSubmitting"
            @click="handleSubmit"
          >
            {{ isSubmitting ? "登录中..." : "立即登录" }}
          </el-button>

          <!-- 第三方登录 -->
          <div class="social-login">
            <div class="divider">
              <span class="divider-text">快速登录</span>
            </div>
            <div class="social-buttons">
              <el-button
                v-for="method in socialMethods"
                :key="method.type"
                circle
                :icon="method.icon"
                @click="handleSocialLogin(method.type)"
              />
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { ElMessage, type FormInstance } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { Login } from "@/api/index.ts";

const router = useRouter();
const route = useRoute();

// 轮播图配置
const bgList = ref([
  { image: "/img/VCG41N1300135335.jpg" },
  { image: "/img/VCG211487249550.jpg" },
  { image: "/img/VCG211412608628.jpg" },
  { image: "/img/VCG211376318837.jpg" },
  { image: "/img/VCG211357890145.jpg" },
  { image: "/img/VCG211356950008.jpg" },
  { image: "/img/VCG211347120608.jpg" },
]);

// 当前轮播图索引
const currentBgIndex = ref(0);

// 表单引用
const formRef = ref<FormInstance>();

// 表单数据
const formData = reactive({
  username: "",
  password: "",
  remember: false,
});

// 提交状态
const isSubmitting = ref(false);

// 第三方登录方式
const socialMethods = [
  { type: "wechat", icon: "ChatRound" },
  { type: "github", icon: "BrandGithub" },
];

// 密码强度计算
const passwordStrength = computed(() => {
  const strength = {
    length: formData.password.length >= 8,
    upper: /[A-Z]/.test(formData.password),
    lower: /[a-z]/.test(formData.password),
    number: /\d/.test(formData.password),
    special: /[^A-Za-z0-9]/.test(formData.password),
  };

  const score = Object.values(strength).filter(Boolean).length;
  return score > 3 ? "强" : score > 1 ? "中" : "弱";
});

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 4, max: 16, message: "长度4-16个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { validator: checkPasswordComplexity, trigger: "blur" },
  ],
};

// 自定义密码验证
function checkPasswordComplexity(rule: any, value: string, callback: any) {
  if (value.length < 6) {
    callback(new Error("密码至少6位"));
  } else if (!/\d/.test(value)) {
    callback(new Error("需包含数字"));
  } else if (!/[A-Za-z]/.test(value)) {
    callback(new Error("需包含字母"));
  } else {
    callback();
  }
}

// 处理表单提交
async function handleSubmit() {
  try {
    await formRef.value?.validate();
    isSubmitting.value = true;

    Login(formData.username, formData.password).then((res) => {
      if (res.code === 200) {
        ElMessage.success("登录成功");

        //存储token
        localStorage.setItem("token", res.data.accessToken);

        router.push("/system/Main/MainView");
      } else {
        ElMessage.error("登录失败，请检查输入");
      }
    });
  } catch (error) {
    ElMessage.error("登录失败，请检查输入");
  } finally {
    isSubmitting.value = false;
  }
}

// 模拟登录API
function mockLogin() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(
        formData.username === "admin" && formData.password === "admin123"
      );
    }, 1500);
  });
}

// 输入框焦点动画
function handleInputFocus(event: Event) {
  const input = event.target as HTMLInputElement;
  input.parentElement?.classList.add("focused");
}

// 轮播图切换回调
function handleCarouselChange(index: number) {
  currentBgIndex.value = index;
}

// 第三方登录处理
function handleSocialLogin(type: string) {
  ElMessage.info(`正在跳转至${type}登录...`);
}

// 密码重置
function showPasswordReset() {
  ElMessage.warning("请联系管理员重置密码");
}
</script>

<style scoped>
/* 基础布局 */
.login-container {
  display: flex;
  min-height: 100vh;
  background: #f8f9fa;
}

.left-panel {
  flex: 1;
  min-width: 60%;
  position: relative;
  overflow: hidden;
}

.right-panel {
  flex: 0 0 40%;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.96);
  box-shadow: -8px 0 32px rgba(0, 0, 0, 0.05);
}

/* 轮播图样式 */
.carousel-content {
  height: 100%;
  transition: transform 0.5s ease;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: opacity 0.8s ease;
}

/* 登录表单样式 */
.login-form {
  width: 400px;
  padding: 40px;
  animation: formSlideIn 0.6s ease;
}

.title {
  font-size: 2rem;
  color: #2c3e50;
  text-align: center;
  margin-bottom: 2rem;
}

.brand {
  color: #409eff;
  font-weight: 700;
}

.version {
  font-size: 0.8rem;
  color: #909399;
  margin-top: 0.5rem;
}

/* 输入框动效 */
.el-input__wrapper {
  transition: all 0.3s ease;
  background: rgba(245, 247, 250, 0.9) !important;
}

.el-input__wrapper:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
}

/* 密码强度提示 */
.password-strength {
  font-size: 0.8rem;
  color: #67c23a;
  margin-top: 0.5rem;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 48px;
  font-size: 1.1rem;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 第三方登录 */
.social-login {
  margin-top: 2rem;
}

.divider {
  position: relative;
  margin: 1.5rem 0;
  text-align: center;
}

.divider-text {
  padding: 0 1rem;
  background: #fff;
  position: relative;
  z-index: 1;
  color: #909399;
}

.divider::before {
  content: "";
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  border-top: 1px solid #dcdfe6;
}

.social-buttons {
  display: flex;
  justify-content: center;
  gap: 1rem;
}

/* 动画 */
@keyframes formSlideIn {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 响应式设计 */
@media (max-width: 992px) {
  .login-container {
    flex-direction: column;
  }

  .left-panel {
    flex: none;
    height: 40vh;
  }

  .right-panel {
    flex: 1;
    padding: 2rem;
    box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.05);
  }

  .login-form {
    width: 100%;
    max-width: 480px;
  }
}

@media (max-width: 480px) {
  .login-form {
    padding: 20px;
  }

  .title {
    font-size: 1.75rem;
  }
}
</style>